<template>
  <div class="my-project-layout">
    <div class="my-project-addProject"
         @click="handleModalAddAction">
      <img :src="newProject"
           alt="">
      <div>创建数据源</div>
    </div>
    <div class="my-list-header">
      <div class="my-list-header_title">
        数据源列表
      </div>
      <div class="my-list-header_mange">
        <el-input size="small"
                  placeholder="搜索"
                  v-model="query.name"
                  @keyup.enter.native="getMySourceList"
                  clearable
                  @change="getMySourceList"></el-input>
      </div>
    </div>
    <el-table :data="sourceList"
              border
              style="width: 100%"
              v-loading="sourceLoading">
      <el-table-column property="name"
                       align="center"
                       label="数据源"
                       width="180" />
      <el-table-column property="db_type"
                       align="center"
                       label="类型"
                       width="180">
        <template #default="scope">
          <el-tag effect="dark"
                  size="small"
                  :type="showDbType(scope.row.db_type)">{{ scope.row.db_type }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center"
                       property="host"
                       label="主机" />
      <el-table-column align="center"
                       property="remark"
                       label="备注" />
      <el-table-column align="center"
                       property="create_timestamp"
                       label="创建时间" />
      <el-table-column align="center"
                       label="操作">
        <template #default="scope">
          <el-button size="mini"
                     type="success"
                     @click="handleModalEditAction(scope.row)">更新</el-button>
          <el-button size="mini"
                     type="danger"
                     plain
                     @click="handleModalDelAction(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination class="common-pagination"
                   v-model:currentPage="pagination.page"
                   :page-size="pagination.size"
                   layout="prev, pager, next, jumper"
                   :total="total"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange">
    </el-pagination>
    <el-dialog v-model="SourceOpModel"
               :title="modalTitle[modalStatus]"
               width="45%"
               destroy-on-close>
      <el-form :model="sourceForm"
               :rules="rules"
               ref="sourceFormRef"
               label-placement="left"
               :label-width="100"
               size="small">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="数据源名称:"
                          prop="name">
              <el-input placeholder="请输入数据源名称"
                        v-model="sourceForm.name"
                        @change="handleFormChange" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据源类型:"
                          prop="db_type">
              <el-select placeholder="请选择数据源类型"
                         v-model="sourceForm.db_type"
                         @change="handleFormChange">
                <el-option v-for="item in sqlTypeList"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务器地址:"
                          prop="host">
              <el-input placeholder="请输入服务器地址"
                        v-model="sourceForm.host"
                        @change="handleFormChange" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务器端口号:"
                          prop="port">
              <el-input-number placeholder="请输入服务器端口号"
                               v-model="sourceForm.port"
                               @change="handleFormChange" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户名:"
                          prop="user">
              <el-input placeholder="请输入用户名"
                        v-model="sourceForm.user"
                        @change="handleFormChange" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码:"
                          prop="password">
              <el-input placeholder="请输入密码"
                        v-model="sourceForm.password"
                        show-password
                        @change="handleFormChange" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据库名称:"
                          prop="db_name">
              <el-input placeholder="请输入数据源名称"
                        v-model="sourceForm.db_name"
                        @change="handleFormChange" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="handleCloseModal"
                   plain
                   size="small"
                   class="footer-modal--btn">取消</el-button>
        <el-button type="primary"
                   size="small"
                   class="footer-modal--btn base-primary-btn"
                   @click="handleTestSource">测试
        </el-button>
        <el-button type="primary"
                   size="small"
                   class="footer-modal--btn  base-primary-btn m_lr_10"
                   v-if="modalStatus === 'add'"
                   v-loading="formLoading"
                   :disabled="!submitFlag"
                   @click="handleAddSource">确认
        </el-button>
        <el-button type="primary"
                   size="small"
                   class="footer-modal--btn  base-primary-btn m_lr_10"
                   v-if="modalStatus === 'edit'"
                   v-loading="formLoading"
                   :disabled="!submitFlag"
                   @click="handleEditSource">更新
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { defineComponent, onMounted, ref } from 'vue'
import {
  addDataSource,
  delDataSource,
  editDataSource,
  getDataSourceList,
  testDataSource,
} from '../../service/source'
import newProject from '../../assets/png/dataSource.jpg'
import { sqlTypeList } from '../../utils/dict'
import { ElMessage, ElMessageBox } from 'element-plus'

export default defineComponent({
  name: 'my-source',
  setup() {
    const sourceLoading = ref(false)
    const formLoading = ref(false)
    const sourceList = ref([])
    const SourceOpModel = ref(false)
    const modalStatus = ref('add')
    const total = ref(0)
    const modalTitle = ref({
      add: '新增数据源',
      edit: '编辑数据源',
    })
    const query = ref({
      name: '',
      size: 10,
      page: 1,
    })
    const handleSizeChange = (pageSize) => {
      query.value.page = 1
      query.value.size = pageSize
      getMySourceList()
    }
    const handleCurrentChange = (page) => {
      query.value.page = page
      getMySourceList()
    }
    const pagination = ref({
      page: 1,
      size: 10,
    })
    const sourceForm = ref({
      name: undefined,
      db_type: undefined,
      host: undefined,
      port: undefined,
      user: undefined,
      password: undefined,
      db_name: undefined,
    })
    const sourceFormRef = ref(null)
    const submitFlag = ref(false)
    const handleFormChange = () => {
      submitFlag.value = false
    }
    const resetForm = () => {
      sourceForm.value = {
        name: undefined,
        db_type: undefined,
        host: undefined,
        port: undefined,
        user: undefined,
        password: undefined,
        db_name: undefined,
      }
    }
    const handleModalAddAction = () => {
      resetForm()
      modalStatus.value = 'add'
      SourceOpModel.value = true
    }
    const handleCloseModal = () => {
      SourceOpModel.value = false
    }
    const getMySourceList = () => {
      sourceLoading.value = true
      getDataSourceList(query.value).then((res) => {
        sourceList.value = res.data.result
        sourceLoading.value = false
        total.value = res.data.total
      })
    }
    const handleTestSource = () => {
      formLoading.value = true
      sourceFormRef.value.validate((valid) => {
        if (valid) {
          testDataSource(sourceForm.value)
            .then((res) => {
              formLoading.value = false
              ElMessage({
                type: 'success',
                message: '连接数据源成功',
              })
              submitFlag.value = true
            })
            .catch(() => {
              ElMessage.error('连接数据源失败')
              formLoading.value = false
            })
        }
      })
    }
    const handleAddSource = () => {
      formLoading.value = true
      sourceFormRef.value.validate((valid) => {
        if (valid) {
          addDataSource(sourceForm.value)
            .then(() => {
              formLoading.value = false
              ElMessage({
                type: 'success',
                message: '新增数据源成功',
              })
              handleCloseModal()
              getMySourceList()
            })
            .catch(() => {
              ElMessage.error('新增数据源失败')
              formLoading.value = false
            })
        }
      })
    }
    const handleModalEditAction = (rowData) => {
      resetForm()
      sourceForm.value = rowData
      modalStatus.value = 'edit'
      submitFlag.value = false
      SourceOpModel.value = true
    }
    const handleEditSource = () => {
      formLoading.value = true
      sourceFormRef.value.validate((valid) => {
        if (valid) {
          editDataSource(sourceForm.value)
            .then(() => {
              formLoading.value = false
              ElMessage({
                type: 'success',
                message: '编辑数据源成功',
              })
              handleCloseModal()
              getMySourceList()
            })
            .catch(() => {
              ElMessage.error('编辑数据源失败')
              formLoading.value = false
            })
        }
      })
    }
    const handleModalDelAction = (rowData) => {
      ElMessageBox.confirm(`你确定删除 ${rowData.name} 么？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        handleDelSource(rowData)
      })
    }
    const showDbType = (type) => {
      let tagType
      switch (type) {
        case 'csv':
          tagType = 'success'
          break
        case 'MySQL':
          tagType = 'warning'
          break
        case 'Oracle':
          tagType = 'error'
          break
        case 'PostgreSQL':
          tagType = 'info'
          break
        default:
          break
      }
      return tagType
    }
    const handleDelSource = (rowData) => {
      delDataSource({ data_source_id: rowData.data_source_id })
        .then(() => {
          ElMessage({
            type: 'success',
            message: '删除数据源成功',
          })
          getMySourceList()
        })
        .catch(() => {
          sourceLoading.value = false
        })
    }
    onMounted(() => {
      getMySourceList()
    })
    return {
      rules: {
        name: {
          required: true,
          trigger: ['blur', 'input'],
          message: '请输入数据源名称',
        },
        db_type: {
          required: true,
          message: '请选择数据源类型',
          trigger: ['change'],
        },
        host: {
          required: true,
          message: '请输入服务器地址',
          trigger: ['input', 'blur'],
        },
        user: {
          required: true,
          message: '请输入用户名',
          trigger: ['input', 'blur'],
        },
        password: {
          required: true,
          message: '请输入密码',
          trigger: ['input', 'blur'],
        },
        db_name: {
          required: true,
          message: '请输入数据库名称',
          trigger: ['input', 'blur'],
        },
      },
      query,
      newProject,
      sourceList,
      SourceOpModel,
      sourceForm,
      submitFlag,
      sourceFormRef,
      modalStatus,
      modalTitle,
      sourceLoading,
      formLoading,
      total,
      handleTestSource,
      handleAddSource,
      handleEditSource,
      sqlTypeList: sqlTypeList,
      pagination,
      handleSizeChange,
      handleCurrentChange,
      getMySourceList,
      handleCloseModal,
      handleModalAddAction,
      handleModalDelAction,
      handleModalEditAction,
      handleFormChange,
      resetForm,
      handleDelSource,
      showDbType,
    }
  },
})
</script>

<style lang="less" scoped>
@import './../../style/page/my-project.less';
</style>
